package com.gl.handler;

import com.alibaba.fastjson.JSON;
import com.gl.common.utils.Result;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;
import java.util.Map;

/**
 * Created by GAOL on 2017/5/13.
 * web层访问log
 */
//@Aspect
//@Component
public class WebLogAspectHandler {

    private static Logger logger = LoggerFactory.getLogger(WebLogAspectHandler.class);

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    /**
     * 定义切面-controller使用了注解RequestMapping的方法
     */
    @Pointcut("execution(public * com.gl.web..*.*(..)) " +
            "and @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void controllerMethodPointcut() {
    }


    /**
     * 请求前打印日志
     *
     * @param joinPoint
     */
    @Before(value = "controllerMethodPointcut()")
    public void doBefore(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = (HttpServletRequest) attributes.getRequest();
        logger.info("*************************Api Request*************************");
        logger.info("RemoteAddr：{}:{}", request.getRemoteAddr(), request.getRemoteHost());
        logger.info("URL：{}", request.getRequestURL().toString());
        logger.info("Method：{}", request.getMethod());
        logger.info("ClassName：{}", joinPoint.getSignature().getDeclaringTypeName());
        Map<String, String[]> params = request.getParameterMap();
        for (String key : params.keySet()) {
            logger.info("Param：{}={}", key, params.get(key));
        }
    }


    /**
     * 请求返回内容
     *
     * @param result
     */
    @AfterReturning(returning = "result", pointcut = "controllerMethodPointcut()")
    public void after(Result result) {
        logger.info("Response：{}", JSON.toJSONString(result));
        long time=System.currentTimeMillis()-startTime.get();
        logger.info("Time：{} ms",time);
    }


}
